package social.hub.util;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class UrlBuilder {

	private String originalUrl;
	private Boolean encodeParans = true;

	private Map<String, String> urlParameters = new LinkedHashMap<String, String>();
	private Map<String, String> queryParameters = new LinkedHashMap<String, String>();

	public UrlBuilder(String url) {
		this.originalUrl = url;
	}

	public UrlBuilder(String url, Boolean encodeParans) {
		this.originalUrl = url;
		this.encodeParans = encodeParans;
	}

	public UrlBuilder addQueryParan(String paran, Object value) {
		if (value != null) {
			queryParameters.put(paran, value.toString());
		}
		return this;
	}

	public UrlBuilder addUrlParan(String paran, Object value) {
		if (value != null) {
			urlParameters.put(paran, value.toString());
		}
		return this;
	}

	public Boolean getEncodeParans() {
		return encodeParans;
	}

	public void setEncodeParans(Boolean encodeParans) {
		this.encodeParans = encodeParans;
	}

	@Override
	public String toString() {

		StringBuilder builder = new StringBuilder();

		parseUrlParans(builder);
		addQueryParans(builder);

		return builder.toString();

	}

	private void addQueryParans(StringBuilder builder) {

		if (!queryParameters.isEmpty()) {

			boolean hasQueryParan = builder.indexOf("?") > 0;

			String caracter = hasQueryParan ? "&" : "?";

			builder.append(caracter);

			for (Entry<String, String> entry : queryParameters.entrySet()) {

				String key = entry.getKey();
				String value = entry.getValue();

				if (value != null) {
					value = encodeParans ? Utils.encode(value) : value;
				} else {
					value = "{" + key + "}";
				}

				String paran = String.format("%s=%s", key, value);
				builder.append(paran).append("&");

			}

		}

	}

	private void parseUrlParans(StringBuilder builder) {

		String text = null;
		String paran = null;
		String name = null;
		int begin = 0;
		int end = 0;
		int pos = 0;
		int length = originalUrl.length();

		while (pos < length) {

			begin = originalUrl.indexOf("{", pos);

			if (begin > 0) {

				end = originalUrl.indexOf("}", begin);

				name = originalUrl.substring(begin + 1, end);
				text = originalUrl.substring(pos, begin);

				paran = urlParameters.get(name);

				if (paran != null) {
					String value = encodeParans ? Utils.encode(paran) : paran;
					builder.append(text).append(value);
				} else {
					builder.append(text).append("{").append(name).append("}");
				}

			} else {

				end = length;

				text = originalUrl.substring(pos);

				builder.append(text);

			}

			pos = end + 1;

		}

	}

}
